<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="生产线名称" prop="productLineName">
        <el-input
          v-model="queryParams.productLineName"
          placeholder="请输入生产线名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['mes:factoryModel:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['mes:factoryModel:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['mes:factoryModel:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['mes:factoryModel:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="factoryModelList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="编号" align="center" prop="id"/>
      <el-table-column label="产品" align="center" prop="product"/>
      <el-table-column label="生产线名称" align="center" prop="productLineName"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['mes:factoryModel:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['mes:factoryModel:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改工厂建模对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item :label-width="'100px'" label="生产线名称" prop="productLineName">
          <el-input v-model="form.productLineName" placeholder="请输入生产线名称"/>
        </el-form-item>
        <el-form-item :label-width="'100px'" label="产品" prop="product">
          <el-input disabled v-model="form.product" placeholder="请选择产品">
            <el-button @click="selectProduct" slot="append">选择</el-button>
          </el-input>
        </el-form-item>
        <el-form-item :label-width="'100px'" label="产品型号" prop="model">
          <el-input disabled v-model="form.model" placeholder="请选择产品"/>
        </el-form-item>
        <el-form-item :label-width="'100px'" label="产品规格" prop="specification">
          <el-input disabled v-model="form.specification" placeholder="请选择产品"/>
        </el-form-item>
        <el-form-item :label-width="'100px'" label="描述" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入描述"/>
        </el-form-item>
        <el-divider content-position="center">工厂建模明细信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddMesFactoryModelDetail">添加
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteMesFactoryModelDetail">删除
            </el-button>
          </el-col>
        </el-row>
        <el-table :data="mesFactoryModelDetailList" :row-class-name="rowMesFactoryModelDetailIndex"
                  @selection-change="handleMesFactoryModelDetailSelectionChange" ref="mesFactoryModelDetail"
        >
          <el-table-column type="selection" width="50" align="center"/>
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="设备" prop="name">
            <template slot-scope="scope">
              <el-form-item :prop="'mesFactoryModelDetailList.'+scope.$index+'.name'" :rules="rules.equipmentId">
                <el-select @change="selectEquipment(scope.$index,scope.row)" v-model="scope.row.name"
                           placeholder="请选择设备"
                >
                  <el-option v-for="item in equipment"
                             :value="item.id"
                             :label="item.name"
                             :key="item.id"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="编码" prop="code">
            <template slot-scope="scope">
              <el-form-item>
                <el-input disabled v-model="scope.row.code" placeholder="请选择设备"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="型号" prop="model">
            <template slot-scope="scope">
              <el-form-item>
                <el-input disabled v-model="scope.row.model" placeholder="请选择设备"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="生产日期" prop="productDate">
            <template slot-scope="scope">
              <el-form-item>
                <el-date-picker clearable
                                disabled
                                v-model="scope.row.productDate"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="请选择设备"
                                style="width: 120px"
                >
                </el-date-picker>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="生产批号" prop="batchNo">
            <template slot-scope="scope">
              <el-form-item>
                <el-input disabled v-model="scope.row.batchNo" placeholder="请选择设备"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="制作商" prop="manufacturer">
            <template slot-scope="scope">
              <el-form-item>
                <el-input disabled v-model="scope.row.manufacturer" placeholder="请选择设备"/>
              </el-form-item>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 选择物料档案 -->
    <MaterialSelect
      :open="openMaterial"
      @onCancel="handleMaterialCancel"
      @onSelected="handleMaterialSelected"
    ></MaterialSelect>
  </div>
</template>

<script>
import {
  addFactoryModel,
  delFactoryModel,
  exportFactoryModel,
  getFactoryModel,
  listFactoryModel,
  updateFactoryModel
} from '@/api/mes/factoryModel'
import MaterialSelect from '@/components/Material/MaterialSelect.vue'
import { getEquipment, listEquipment } from '@/api/mes/equipment'

export default {
  name: 'FactoryModel',
  components: { MaterialSelect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedMesFactoryModelDetail: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工厂建模表格数据
      factoryModelList: [],
      // 工厂建模明细表格数据
      mesFactoryModelDetailList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productLineName: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        product: [
          { required: true, message: '产品不能为空', trigger: 'blur' }
        ],
        productLineName: [
          { required: true, message: '生产线名称不能为空', trigger: 'blur' }
        ],
        equipmentId: [
          { required: true, message: '设备不能为空', trigger: 'blur' }
        ]
      },
      // 打开选择物料
      openMaterial: false,
      // 设备
      equipment: []
    }
  },
  created() {
    this.getList()
    this.getEquipment()
  },
  watch: {
    'mesFactoryModelDetailList': {
      handler(newVal, oldVal) {
        this.form.mesFactoryModelDetailList = newVal
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    selectEquipment(index, { name }) {
      //index 是操作的详细信息数组的索引 name是设备主键id
      getEquipment(name).then(res => {
        this.$set(this.mesFactoryModelDetailList, index, res.data)
      })
    },
    handleMaterialCancel() {
      this.openMaterial = false
    },
    handleMaterialSelected(list) {
      if (list && list.length > 0) {
        const material = list[0]
        this.form = {
          ...this.form,
          materialId: material.id,
          product: material.name,
          model: material.model,
          specification: material.specification
        }
      }
      this.openMaterial = false
    },
    selectProduct() {
      this.openMaterial = true
    },
    /** 查询工厂建模列表 */
    getList() {
      this.loading = true
      listFactoryModel(this.queryParams).then(response => {
        this.factoryModelList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    getEquipment() {
      listEquipment().then(res => {
        this.equipment = res.rows
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        materialId: null,
        productLineName: null,
        remark: null,
        mesFactoryModelDetailList: []
      }
      this.mesFactoryModelDetailList = []
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加工厂建模'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getFactoryModel(id).then(response => {
        this.form = response.data
        this.mesFactoryModelDetailList = response.data.mesFactoryModelDetailList
        this.open = true
        this.title = '修改工厂建模'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {

          if (this.form.id != null) {
            updateFactoryModel(this.form).then(response => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addFactoryModel(this.form).then(response => {
              this.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认删除工厂建模编号为"' + ids + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delFactoryModel(ids)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      })
    },
    /** 工厂建模明细序号 */
    rowMesFactoryModelDetailIndex({ row, rowIndex }) {
      row.index = rowIndex + 1
    },
    /** 工厂建模明细添加按钮操作 */
    handleAddMesFactoryModelDetail() {
      let obj = {}
      obj.equipmentId = ''
      this.mesFactoryModelDetailList.push(obj)
    },
    /** 工厂建模明细删除按钮操作 */
    handleDeleteMesFactoryModelDetail() {
      if (this.checkedMesFactoryModelDetail.length === 0) {
        this.$alert('请先选择要删除的工厂建模明细数据', '提示', { confirmButtonText: '确定' })
      } else {
        this.mesFactoryModelDetailList = this.mesFactoryModelDetailList.filter(item => {
          return !this.checkedMesFactoryModelDetail.some(item2 => item2.index === item.index)
        })
      }
    },
    /** 单选框选中数据 */
    handleMesFactoryModelDetailSelectionChange(selection) {
      this.checkedMesFactoryModelDetail = selection
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出所有工厂建模数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return exportFactoryModel(queryParams)
      }).then(response => {
        this.download(response.msg)
      })
    }
  }
}
</script>
